<template>
  <div class="order-management">
    <el-card>
      <template #header>
        <div class="search-form">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索订单..."
            clearable
            @clear="handleSearch"
          />
          <el-select
            v-model="searchForm.status"
            placeholder="订单状态"
            clearable
          >
            <el-option label="待支付" :value="0" />
            <el-option label="已支付" :value="1" />
            <el-option label="配送中" :value="2" />
            <el-option label="已完成" :value="3" />
            <el-option label="已取消" :value="4" />
          </el-select>
          <el-date-picker
            v-model="searchForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </div>
      </template>

      <el-table
        :data="orders.records"
        v-loading="loading"
        @sort-change="handleSortChange"
      >
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="totalAmount" label="总金额" width="100">
          <template #default="scope">
            ¥{{ scope.row.totalAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="deliveryLocation" label="送达" show-overflow-tooltip />
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button 
              v-if="scope.row.status === 0"
              type="warning" 
              size="small" 
              @click="handlePay(scope.row)"
            >
              支付
            </el-button>
            <el-button 
              v-if="scope.row.status === 1"
              type="success" 
              size="small" 
              @click="handleDelivery(scope.row)"
            >
              配送
            </el-button>
            <el-button 
              v-if="scope.row.status === 2"
              type="success" 
              size="small" 
              @click="handleComplete(scope.row)"
            >
              完成
            </el-button>
            <el-button 
              v-if="[0,1,2].includes(scope.row.status)"
              type="danger" 
              size="small" 
              @click="handleCancel(scope.row)"
            >
              取消
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="orders.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSearch"
          @current-change="handleSearch"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="订单详情"
      width="600px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="订单编号">{{ currentOrder.id }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ currentOrder.username }}</el-descriptions-item>
        <el-descriptions-item label="送达地点">{{ currentOrder.deliveryLocation }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getStatusType(currentOrder.status)">
            {{ getStatusText(currentOrder.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDate(currentOrder.createdAt) }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ formatDate(currentOrder.updatedAt) }}
        </el-descriptions-item>
      </el-descriptions>

      <el-table :data="currentOrder.orderItems || []" style="margin-top: 20px">
        <el-table-column prop="snackName" label="商品" />
        <el-table-column prop="quantity" label="数量" width="100" />
        <el-table-column prop="price" label="单价" width="100">
          <template #default="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column label="小计" width="100">
          <template #default="scope">
            ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>

      <div class="total-amount">
        总计：¥{{ currentOrder.totalAmount?.toFixed(2) }}
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { formatDateTime } from '@/utils/dateUtil'
import dayjs from 'dayjs'

const searchForm = reactive({
  keyword: '',
  status: null,
  dateRange: [],
  sortField: 'created_at',
  sortOrder: 'desc'
})

const loading = ref(false)
const orders = ref({ records: [], total: 0 })
const dialogVisible = ref(false)
const currentOrder = ref({})
const currentPage = ref(1)
const pageSize = ref(10)

const formatDate = (date) => {
  if (!date) return '-';
  try {
    // 确保日期是合法的
    const dateObj = new Date(date);
    if (isNaN(dateObj.getTime())) {
      return date; // 如果日期无效，则返回原始字符串
    }
    
    // 使用更可靠的格式化方式
    const year = dateObj.getFullYear();
    const month = String(dateObj.getMonth() + 1).padStart(2, '0');
    const day = String(dateObj.getDate()).padStart(2, '0');
    const hours = String(dateObj.getHours()).padStart(2, '0');
    const minutes = String(dateObj.getMinutes()).padStart(2, '0');
    const seconds = String(dateObj.getSeconds()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  } catch (error) {
    console.error('日期格式化错误:', error);
    return date; // 发生错误时返回原始值
  }
}

const getStatusType = (status) => {
  switch (parseInt(status)) {
    case 0: return 'info'
    case 1: return 'warning'
    case 2: return 'primary'
    case 3: return 'success'
    case 4: return 'danger'
    default: return 'info'
  }
}

const getStatusText = (status) => {
  switch (parseInt(status)) {
    case 0: return '待支付'
    case 1: return '已支付'
    case 2: return '配送中'
    case 3: return '已完成'
    case 4: return '已取消'
    default: return '未知'
  }
}

const handleSearch = async () => {
  try {
    loading.value = true
    
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      keyword: searchForm.keyword,
      status: searchForm.status,
      sortField: searchForm.sortField,
      sortOrder: searchForm.sortOrder
    }
    
    // 添加时间范围参数
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startTime = dayjs(searchForm.dateRange[0]).format('YYYY-MM-DD HH:mm:ss')
      params.endTime = dayjs(searchForm.dateRange[1]).format('YYYY-MM-DD HH:mm:ss')
    }
    
    console.log('发送查询参数:', params)
    const res = await request.post('/admin/orders/search', params)
    
    if (res.code === 200) {
      orders.value = res.data
    }
  } catch (error) {
    console.error('Failed to search orders:', error)
    ElMessage.error('搜索订单失败')
  } finally {
    loading.value = false
  }
}

// 排序处理
const handleSortChange = ({ prop, order }) => {
  searchForm.sortField = prop
  searchForm.sortOrder = order === 'ascending' ? 'asc' : 'desc'
  handleSearch()
}

const handleView = async (order) => {
  try {
    const res = await request.get(`/admin/orders/${order.id}`)
    if (res.code === 200) {
      currentOrder.value = res.data
      dialogVisible.value = true
    }
  } catch (error) {
    console.error('Failed to load order detail:', error)
    ElMessage.error('加载订单详情失败')
  }
}

const handlePay = (order) => {
  ElMessageBox.confirm('确认支付该订单？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await request.put(`/admin/orders/${order.id}/status`, { status: 1 })
      ElMessage.success('订单已支付')
      handleSearch()
    } catch (error) {
      console.error('Failed to pay order:', error)
      ElMessage.error('操作失败')
    }
  })
}

const handleDelivery = (order) => {
  ElMessageBox.confirm('确认开始配送该订单？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await request.put(`/admin/orders/${order.id}/status`, { status: 2 })
      ElMessage.success('订单已开始配送')
      handleSearch()
    } catch (error) {
      console.error('Failed to start delivery:', error)
      ElMessage.error('操作失败')
    }
  })
}

const handleComplete = (order) => {
  ElMessageBox.confirm('确认完成该订单？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await request.put(`/admin/orders/${order.id}/status`, { status: 3 })
      ElMessage.success('订单已完成')
      handleSearch()
    } catch (error) {
      console.error('Failed to complete order:', error)
      ElMessage.error('操作失败')
    }
  })
}

const handleCancel = (order) => {
  ElMessageBox.confirm('确认取消该订单？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await request.put(`/admin/orders/${order.id}/status`, { status: 4 })
      ElMessage.success('订单已取消')
      handleSearch()
    } catch (error) {
      console.error('Failed to cancel order:', error)
      ElMessage.error('操作失败')
    }
  })
}

const handleDelete = async (row) => {
  ElMessageBox.confirm('确定要删除该订单吗？此操作不可恢复。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await request.delete(`/admin/orders/${row.id}`)
      ElMessage.success('订单删除成功')
      handleSearch()
    } catch (error) {
      console.error('删除订单失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

handleSearch()
</script>

<style scoped>
.order-management {
  padding: 20px;
}

.search-form {
  display: flex;
  align-items: center;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.total-amount {
  margin-top: 20px;
  text-align: right;
  font-weight: bold;
  font-size: 16px;
}
</style> 